package com.jeomo.common.quartz.starter.listener;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.TriggerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <h3>springboot-quartz</h3>
 * <p>Trigger监听器日志</p>
 *
 * @author : 崔贺
 * @date : 2020-08-18 09:10
 **/
public class LogTriggerListener implements TriggerListener {

    private static Logger log = LoggerFactory.getLogger(LogTriggerListener.class);

    @Override
    public String getName() {
        return "MonitorTriggerListener";
    }

    /**
     * (1)
     * Trigger被激发 它关联的job即将被运行
     */
    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext context) {
        try {
            JobDetail jobDetail = context.getJobDetail();
            log.debug("Trigger被激发****执行任务类为：" + jobDetail.getKey().getClass().toString());
        } catch (Exception e) {
            log.error("Trigger被激发时异常" + context.getJobDetail().getKey().getClass().toString(), e);
        } catch (Throwable e) {
            log.error("Trigger被激发时出错" + context.getJobDetail().getKey().getClass().toString(), e);
        }

    }

    /**
     * (2)
     * Trigger被激发 它关联的job即将被运行,先执行(1)，在执行(2)
     * 如果返回TRUE 那么任务job会被终止
     */

    @Override
    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
        return false;
    }

    /**
     * (3) 当Trigger错过被激发时执行,比如当前时间有很多触发器都需要执行，
     * 但是线程池中的有效线程都在工作，
     * 那么有的触发器就有可能超时，错过这一轮的触发。
     */
    @Override
    public void triggerMisfired(Trigger trigger) {
        log.debug("：超时！超时！超时！超时！超时！！" + trigger.getClass().getName());
    }

    /**
     * (4) 任务完成时触发
     */
    @Override
    public void triggerComplete(Trigger trigger, JobExecutionContext context, Trigger.CompletedExecutionInstruction triggerInstructionCode) {
        try {
            JobDetail jobDetail = context.getJobDetail();
            log.debug("*Trigger被激发*任务执行完毕：" + jobDetail.getKey().getClass().toString());
        } catch (Exception e) {
            log.error("trigger完成时异常" + context.getJobDetail().getKey().getClass().toString(), e);
        } catch (Throwable e) {
            log.error("trigger完成时出错" + context.getJobDetail().getKey().getClass().toString(), e);
        }
    }

}
